package com.tnl.hunter.webchat.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.hunter.db.entity.Dictionary;
import com.biz.system.config.QiNiuConfig;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.tnl.hunter.dto.ErrorMsg;
import com.tnl.hunter.webchat.utils.SMSService;
import com.tnl.hunter.webchat.utils.WxaTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class JobController {

    private static final Logger logger = LoggerFactory.getLogger(JobController.class);

    @Autowired
    private WXUserDAO userDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private JobTitleDAO roleDAO;
    @Autowired
    private EmployerDAO employerDAO;
    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private RecommendDAO recomDAO;
    @Autowired
    private InterViewDAO interviewDAO;
    @Autowired
    private PersonDAO personDAO;
    @Autowired
    private EmployeeDAO employeeDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private InterViewRecordDAO interViewRecordDAO;

    @Autowired
    private SysConfigRepo sysConfigService;

    @Autowired
    private TbFileDAO tbFileDAO;

    @Autowired
    private DictionaryDAO dictionaryDAO;

    // ============菜单入口: 发布职位
    // 发布职位-显示发布职位表单
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toCreateJob.page", method = RequestMethod.GET)
    public String publishJob(HttpServletRequest request, Model model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        // 获取自己的信息，HR是一个employer
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            /*
             * Employer newItem = new Employer(); newItem.setOpenid(openid); model.addAttribute("employer", newItem); return
             * "wechat/headhunter/hr/hrxinxi1";
             */
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            if (employer.getBinded() != 1) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
                return "wechat/headhunter/msgpage";
            }

            int companyid = employer.getCompanyId();
            Company company = null;
            if (companyid > 0) {
                company = companyDAO.getById(companyid);
            }
            if (companyid <= 0 || company == null) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证中，暂时不能发布职位信息。");
                return "wechat/headhunter/msgpage";
            }

            int domainid = company.getDomain();
            if (domainid <= 0) {
                model.addAttribute("title", "温馨提示");
                model.addAttribute("msg", "您的公司信息有错，请联系客服（微信ID:ElenaYu807）修改公司信息。");
                return "wechat/headhunter/msgpage";
            }
            Domain domain = domainDAO.getById(domainid);
            if (domain == null) {
                model.addAttribute("msg", "您的公司信息有错，请联系客服（微信ID:ElenaYu807）修改公司信息。");
                return "wechat/headhunter/msgpage";
            }

            model.addAttribute("employer", employer);
            JobDesc job = new JobDesc();

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, +1);
            Date expireDate = calendar.getTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String expireStr = format.format(expireDate);
            long expiretime = expireDate.getTime();

            job.setExpiredDate(expiretime);
            job.setExpiredDateStr(expireStr);
            job.setName("");
            // jobdesc里面的domainid用的是第一级的专业领域（医疗/医药）
            // 直通车职位匹配以此为主
            job.setDomainID(domain.getId());
            int domainId = domainDAO.getRootDomainId(domainid);
            List<Domain> domains = domainDAO.getAllSubDomain(domainId);
            logger.debug("domain" + domainId + "subdomain is " + domainid);
            model.addAttribute("domains", domains);

            List<Company> companies = companyDAO.getDomainCompanies(domainId);

            List<City> cities = cityDAO.getALL();
            List<JobTitle> roles = roleDAO.getALL();
            List<Dictionary> tags = dictionaryDAO.getByType("position_slogan");
            model.addAttribute("companies", companies);
            model.addAttribute("cities", cities);
            model.addAttribute("roles", roles);
            model.addAttribute("position", job);
            model.addAttribute("tags", tags);

            /* */
            String ticket = sysConfigService.getJsTicket();
            logger.debug("js api ticket is " + ticket);
            String url = request.getRequestURL().toString();
            if (!StringUtils.isEmpty(request.getQueryString())) {
                url = url + "?" + request.getQueryString();
            }
            url = url.replace("http", "https");
            logger.debug("request url is " + url);

            Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

            jsConfig config = new jsConfig();
            config.setAppid(WebchatServiceConstant.APPID);
            config.setCurrenttimestamp(jsconfig.get("timestamp"));
            config.setNonceStr(jsconfig.get("nonceStr"));
            config.setSignatureStr(jsconfig.get("signature"));

            model.addAttribute("config", config);
            /* */

            return "wechat/headhunter/hr/fabuzhiwei";
        }
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/getCompanyByDomain.do", method = RequestMethod.POST)
    @ResponseBody
    public ErrorMsg getCompanyByDomain(HttpServletRequest request, Integer majorDomainId1,
                                       Integer majorDomainId2, Integer majorDomainId3) {
        ErrorMsg msg = new ErrorMsg();
        List<Company> companies = new ArrayList<>();
        List<Integer> domainIds = new ArrayList<>();
        if (majorDomainId1 != null) {
            domainIds.add(majorDomainId1);
        }

        if (majorDomainId2 != null) {
            domainIds.add(majorDomainId2);
        }
        if (majorDomainId3 != null) {
            domainIds.add(majorDomainId3);
        }
        if (domainIds.size() > 0) {
            companies = companyDAO.getListByDomainIds(domainIds);
        } else {
            companies = companyDAO.getALL();
        }
        msg.setData(companies);
        msg.setErrorcode("1");
        return msg;

    }


    // 创建职位
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/creatJob.do", method = RequestMethod.POST)
    public @ResponseBody
    ErrorMsg createJobDesc(HttpServletRequest request, ModelMap model, JobDesc job) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("创建职位失败");
            return msg;
        }

        String jobname = job.getName();
        if (StringUtils.isEmpty(jobname)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("职位名不能为空");
            return msg;
        }
        //JobTitle jobtitle = roleDAO.getByName(jobname);//update by 20191120 临时调整职位归一：由后台进行归一调整前台职位归一新增字段职位类别
        //if (jobtitle == null) {
        // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
        job.setName(jobname);
        job.setRoleid(job.getRoleid());
        //} else {
        // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
        //job.setName(jobname);
        //job.setRoleid(jobtitle.getId());
        //}
        JobTitle jobT = roleDAO.getById(job.getExpectJobId());
        if (jobT == null) {
            // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
//      job.setExpectJob(job.get);
            job.setExpectJobId(0);
        } else {
            // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
//      job.setExpectJob(jobname);
            job.setExpectJobId(jobT.getId());
        }
        /*
         * if(job.getRoleid() > 0) { role = roleDAO.getById(job.getRoleid()); if(role != null) {
         * job.setName(role.getName()); } }
         */

        Date now = new Date();
        job.setCreateDate(now.getTime());
        String dateStr = job.getExpiredDateStr();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(dateStr);
            job.setExpiredDate(date.getTime());
        } catch (ParseException e) {
            msg.setErrorcode("500101");
            msg.setMsg("创建职位失败");
            return msg;
        }
        job.setCreatedby(employer.getId());

        int companyId = employer.getCompanyId();
        job.setCompanyId(companyId);

        // 这里要一个流水线号
        // Random rand = new Random();
        // String code = Integer.toString(rand.nextInt(99));
        String code = jobDAO.getJobCodeString();
        job.setJobCode("P-" + code);
        job.setStatus(1);
        int id = jobDAO.save(job);
        if (id == -1) {
            msg.setErrorcode("-1");
            msg.setMsg("创建职位失败");
            return msg;
        }
        job.setId(id);
        msg.setErrorcode("0");
        msg.setMsg("成功创建职位");
        msg.setData(job);

        return msg;
    }


    // 显示详细职位信息(职位创建成功后)TODO
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toShowCandidates.page", method = RequestMethod.GET)
    public String toShowCandidates(HttpServletRequest request, ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }
        // JobDesc jd = jobDAO.getById(positionid);
        // if (jd == null) {
        // logger.error("can't find the job with the id " + positionid);
        // return "wechat/headhunter/errorpage";
        // }

        model.addAttribute("employer", employer);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        // job title

        List<Employee> emps = employeeDAO.searchEmployeesByhr(employer);
        model.addAttribute("emps", emps);


        return "wechat/headhunter/hr/fabuzhiwei2";
    }

    // 编辑职位
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toEditJob.page", method = RequestMethod.GET)
    public String toEditJob(HttpServletRequest request, int positionid, ModelMap model) {
        HttpSession session = request.getSession();
//        String openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        JobDesc jd = jobDAO.getById(positionid);
        if (jd == null) {
            logger.error("can't find the Recommendation with the id " + positionid);
            return "wechat/headhunter/errorpage";
        }
        long time = jd.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        // String str = DateUtil.getDateTimeStr(time);
        jd.setExpiredDateStr(str);

        int companyId = jd.getCompanyId();
        Company comp = this.companyDAO.getById(companyId);
        comp.getDomain();

        List<Company> companies = companyDAO.getALL();
        List<City> cities = cityDAO.getALL();
        List<JobTitle> roles = roleDAO.getALL();
        List<Dictionary> tags = dictionaryDAO.getByType("position_slogan");
        model.addAttribute("companies", companies);
        model.addAttribute("cities", cities);
        model.addAttribute("roles", roles);
        model.addAttribute("tags", tags);

        model.addAttribute("position", jd);
        List<Domain> domains = domainDAO.getAllSubDomain();
        model.addAttribute("domains", domains);
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hr/fabuzhiwei";
    }

    // 更新职位
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/updateJob.do", method = RequestMethod.POST)
    public @ResponseBody
    ErrorMsg updateJobDesc(HttpServletRequest request, ModelMap model, JobDesc job) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("您尚未提交认证信息");
            return msg;
        }

        long jobId = job.getId();
        JobDesc jobdesc = jobDAO.getById(jobId);
        if (jobdesc == null) {
            msg.setErrorcode("500101");
            msg.setMsg("选择的职位不存在");
            return msg;
        }
        // 查看用户是否有权限编辑job{}
        int empId = employer.getId();
        int createrId = jobdesc.getCreatedby();
        if (createrId != empId) {
            logger.error("can't eidt the job id=" + job.getId());
            msg.setErrorcode("300101");
            msg.setMsg("你无权编辑这个职位");
            return msg;
        }

        String jobname = job.getName();
        if (StringUtils.isEmpty(jobname)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("职位名不能为空");
            return msg;
        }
        //JobTitle jobtitle = roleDAO.getByName(jobname);
        //if (jobtitle == null) {
        // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
        job.setName(jobname);//update by adela 20191120  临时调整职位归一：由后台进行归一调整前台职位归一新增字段职位类别
        job.setRoleid(job.getRoleid());
        job.setStatus(1);
        //} else {
        // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
        //job.setName(jobname);
        //job.setRoleid(jobtitle.getId());
        //}
        /*
         * if(job.getRoleid() > 0) { role = roleDAO.getById(job.getRoleid()); if(role != null) {
         * job.setName(role.getName()); } }
         */

        String dateStr = job.getExpiredDateStr();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(dateStr);
            job.setExpiredDate(date.getTime());
        } catch (ParseException e) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未认证个人信息");
            return msg;
        }
        convertJobDesc(jobdesc, job);

        int row = jobDAO.update(jobdesc);
        if (row == -1) {
            msg.setErrorcode("-2");
            msg.setMsg("更新数据库出错");
            return msg;
        }

        msg.setErrorcode("0");
        msg.setData(jobdesc);

        return msg;
    }

    // 暂停职位
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/holdJobDesc.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> holdJobDesc(HttpServletRequest request, ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们服务");
            return returnMap;
        }

        Integer jobid = Integer.valueOf(request.getParameter("jobid"));
        Integer status = Integer.valueOf(request.getParameter("status"));
        if (StringUtils.isEmpty(jobid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定职位");
            return returnMap;
        }
        int result = 0;
        if (status == 0) {
            result = jobDAO.holdJob(jobid);
        } else {
            result = jobDAO.publishJob(jobid);
        }


        if (result == 1) {
            returnMap.put("errorcode", 0);
            returnMap.put("msg", "成功获取数据");
        } else {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "操作失败");
        }

        return returnMap;
    }

    private void convertJobDesc(JobDesc jobdesc, JobDesc job) {
        jobdesc.setName(job.getName());
        jobdesc.setRoleid(job.getRoleid());
        jobdesc.setCityId(job.getCityId());
        jobdesc.setLocation(job.getLocation());
        jobdesc.setMajorDuty(job.getMajorDuty());
        jobdesc.setEmployeeNum(job.getEmployeeNum());
        jobdesc.setAnnualPayment(job.getAnnualPayment());
        jobdesc.setReward(job.getReward());
        jobdesc.setStatus(job.getStatus());
        jobdesc.setExpectcompanyid(job.getExpectcompanyid());
        jobdesc.setExpectcompanyid2(job.getExpectcompanyid2());
        jobdesc.setExpectcompanyid3(job.getExpectcompanyid3());
        jobdesc.setDescription(job.getDescription());
        jobdesc.setComment(job.getComment());
        jobdesc.setExpiredDate(job.getExpiredDate());
        jobdesc.setPlatformID(job.getPlatformID());
        jobdesc.setExpectJob(job.getExpectJob());
        jobdesc.setExpectJobId(job.getExpectJobId());
        jobdesc.setMajorDomainId1(job.getMajorDomainId1());
        jobdesc.setMajorDomainId2(job.getMajorDomainId2());
        jobdesc.setMajorDomainId3(job.getMajorDomainId3());
        jobdesc.setKeywords(job.getKeywords());

    }

    // ==============菜单入口：职位列表
    // 发布的悬赏职位列表
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/joblist.page", method = RequestMethod.GET)
    public String jobList(HttpServletRequest request, ModelMap model, @RequestParam(value = "value=status", defaultValue = "1") Integer status) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
//        openid="o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }
        if (employer.getBinded() != 1) {
            model.addAttribute("title", "信息审核中");
            model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
            return "wechat/headhunter/msgpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");

        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }

        List<JobDesc> list = jobDAO.getJobDescCreatedBy(employer.getId(), offset, status);

//        List<JobDesc> holdJobList = jobDAO.getJobDescCreatedByStatus(employer.getId(),offset, 1);
        List<Domain> domains = domainDAO.getALL();
        if (list != null) {
            for (JobDesc job : list) {
                long time = job.getExpiredDate();
                Date date = new Date(time);
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String str = bartDateFormat.format(date);
                job.setExpiredDateStr(str);

                long createDate = job.getCreateDate();
                job.setCreateDateStr(bartDateFormat.format(new Date(createDate)));

                logger.info("jobCreateDate:" + createDate + "-------------- formatDate:" + bartDateFormat.format(new Date(createDate)));
            }
        } else {
            list = new ArrayList<JobDesc>();
        }
        List<JobDesc> jobList = list.parallelStream().filter(s -> s.getStatus() > 0).collect(Collectors.toList());
        list.removeAll(jobList);
//        List<JobDesc>
//        map.forEach((key,value)->{
//            if (key > 0){
//
//            }
//        });
        List<City> cities = cityDAO.getALL();
        model.addAttribute("jobList", jobList);
        model.addAttribute("cities", cities);
        model.addAttribute("domains", domains);
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hr/joblist";
    }

    // 获取更多我的悬赏的列表信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/moreJob.do", method = RequestMethod.GET)
    public @ResponseBody
    ErrorMsg moreJobList(HttpServletRequest request, ModelMap model) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未提交认证信息");
            return msg;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        List<JobDesc> list = jobDAO.getJobDescCreatedBy(employer.getId(), offset, 1);
        if (list != null) {
            for (JobDesc job : list) {
                long time = job.getExpiredDate();
                Date date = new Date(time);
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String str = bartDateFormat.format(date);
                job.setExpiredDateStr(str);
                //city
                long createDate = job.getCreateDate();
                job.setCreateDateStr(bartDateFormat.format(new Date(createDate)));

                int cityId = job.getCityId();
                City city = cityDAO.getById(cityId);
                job.setCity(city);
                Domain domain = domainDAO.getById(job.getDomainID());
                job.setDomainName(domain.getName());
            }
        } else {
            list = new ArrayList<JobDesc>();
        }
        // this.convertJob(jobdesc, job);
        msg.setErrorcode("0");
        msg.setMsg("获取数据成功");
        msg.setData(list);

        return msg;
    }


    // 职位候选人列表，点击后查看详细的职位信息及被推荐人列表
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toJobView.do", method = RequestMethod.GET)
    public String infoOfJobwithRecommends(HttpServletRequest request, Integer jobid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");
        // String openid="o852Is7CAaACPsK06dWq5NUKlC";
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (jobid == null || jobid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择的职位");
            return "wechat/headhunter/msgpage";
        }
        JobDesc job = jobDAO.getById(jobid);
        System.out.println(job.getDomainID());
        if (job == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的职位不存在");
            return "wechat/headhunter/msgpage";
        }

        long time = job.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        job.setExpiredDateStr(str);

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(jobid, 0);

        Company company = companyDAO.getById(job.getExpectcompanyid());

        List<City> cities = cityDAO.getALL();

        model.addAttribute("job", job);
        model.addAttribute("cities", cities);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);


        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */
        List<EmployeePerson> emps = searchDiffEmployeesByJob(job, jobid);//update by adela 20191120 会猎端HR，查看职位列表，更多系统匹配候选人栏，候选人人数与PC端不一致，两端需同步
        List<List<EmployeePerson>> resList = new ArrayList<List<EmployeePerson>>();
        List<EmployeePerson> temp = new ArrayList<EmployeePerson>();

        if (emps != null && emps.size() < 3) {
            resList.add(emps);
            model.addAttribute("emps", resList);
        } else {
            for (int i = 0; i < emps.size(); i++) {
                temp.add(emps.get(i));
                if ((i + 1) % 3 == 0) {
                    resList.add(temp);
                    temp = new ArrayList<EmployeePerson>();
                } else if (i == (emps.size() - 1)) {
                    resList.add(temp);
                }
            }
            model.addAttribute("emps", resList);
        }

        model.addAttribute("empslength", emps.size());
        return "wechat/headhunter/hr/zhiweixiangxixinxi";
    }

    public List<EmployeePerson> searchDiffEmployeesByJob(JobDesc job, Integer jobid) {
        List<EmployeePerson> empsin = new ArrayList<EmployeePerson>();
        List<EmployeePerson> emps = employeeDAO.searchDiffEmployeesByJob(job, jobid, 1);
        //update by adela 20191120 会猎端HR，查看职位列表，更多系统匹配候选人栏，候选人人数与PC端不一致，两端需同步
        if (job.getDomainID() != 0 && emps != null) {
            Integer jobDomainId = getBaseDomainById(job.getDomainID());
            for (EmployeePerson employeePerson : emps) {
                if (employeePerson.getActive() == 1) {
                    Integer empDomainId = 0;
                    if (employeePerson.getDomainId() != 0) {
                        if (employeePerson.getDomainId() == 1 || employeePerson.getDomainId() == 2) {
                            empDomainId = employeePerson.getDomainId();
                        } else {
                            empDomainId = getBaseDomainById(employeePerson.getDomainId());
                        }
                        if (jobDomainId == empDomainId) {
                            System.out.println("系统匹配到候选人 编号：" + employeePerson.getId() + " 姓名：" + employeePerson.getName());
                            empsin.add(employeePerson);
                        }
                    }
                }
            }
        }
        return empsin;
    }

    /**
     * get base domainid
     *
     * @param domainId
     * @return
     */
    public Integer getBaseDomainById(Integer domainId) {
        Domain domain = domainDAO.getById(domainId);
        return domain.getParentId();
    }

    //职位候选人列表，点击后查看详细的职位信息及被推荐人列表
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toViewRecommend.do", method = RequestMethod.GET)
    public String viewRecommend(HttpServletRequest request, Integer positionid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (positionid == null || positionid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择的职位");
            return "wechat/headhunter/msgpage";
        }
        JobDesc job = jobDAO.getById(positionid);
        if (job == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的职位不存在");
            return "wechat/headhunter/msgpage";
        }

        long time = job.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        job.setExpiredDateStr(str);

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(positionid, 0);

        Company company = companyDAO.getById(job.getExpectcompanyid());

        List<City> cities = cityDAO.getALL();

        model.addAttribute("job", job);
        model.addAttribute("cities", cities);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

//   List<Employee> emps = employeeDAO.searchEmployeesByJob(job);
//   model.addAttribute("emps", emps);

        return "wechat/headhunter/hr/recommendList";
    }

    //显示详细职位和候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toViewJob.page", method = RequestMethod.GET)
    public String toShowJobWithCandidate(HttpServletRequest request, int positionid, ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的服务。");
            return "wechat/headhunter/msgpage";
        }
        JobDesc jd = jobDAO.getById(positionid);
        if (jd == null) {
            logger.error("can't find the job with the id " + positionid);
            return "wechat/headhunter/errorpage";
        }
        int cityid = jd.getCityId();
        City city = cityDAO.getById(cityid);
        jd.setCity(city);

        int companyid = jd.getCompanyId();
        Company company = companyDAO.getById(companyid);
        if (company != null) {
            jd.setCompanyName(company.getName());
        }

        int expcompanyid = jd.getExpectcompanyid();
        Company expCompany = companyDAO.getById(expcompanyid);
        jd.setExpCompanyName(expCompany.getName());

        if (!StringUtils.hasText(jd.getName())) {
            long roleid = jd.getRoleid();
            JobTitle role = roleDAO.getById(roleid);
            jd.setRole(role);
            jd.setName(role.getName());
        }
        long time = jd.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        // String str = DateUtil.getDateTimeStr(time);
        jd.setExpiredDateStr(str);

        model.addAttribute("employer", employer);

        model.addAttribute("position", jd);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */
        // job title
        List<EmployeePerson> emps = searchDiffEmployeesByJob(jd, positionid);
        model.addAttribute("emps", emps);

        return "wechat/headhunter/hr/fabuzhiwei2";
    }

    // 获取更多职位的候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/moreJobRecommend.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> moreJobRecommendation(HttpServletRequest request, ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            returnMap.put("errorcode", 500101);
            returnMap.put("msg", "你尚未注册我们的服务");
            return returnMap;
        }

        Integer jobid = Integer.valueOf(request.getParameter("jobid"));
        if (StringUtils.isEmpty(jobid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定职位");
            return returnMap;
        }

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(jobid, offset);

        returnMap.put("errorcode", 0);
        returnMap.put("msg", "成功获取数据");
        returnMap.put("recommends", list);

        return returnMap;
    }

    // 候选人的面试状态
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/toInterview.do", method = RequestMethod.GET)
    public String infoOfInterview(HttpServletRequest request, Integer recommendid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "o852IsyRIkwuLXZox-Z1ounYjDEc");
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (recommendid == null || recommendid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择哪个职位");
            return "wechat/headhunter/msgpage";
        }

        Recommendation recommend = recomDAO.getById(recommendid.toString());
        if (recommend == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的推荐不存在");
            return "wechat/headhunter/msgpage";
        }

        Person person = personDAO.getById(recommend.getPersonId());
        if (person != null) {
            long roleId = person.getRoleId();
            JobTitle role = roleDAO.getById(roleId);
            if (role != null) {
                person.setRoleName(role.getName());
            }
        }

        //List<Interview> list = interviewDAO.getByKey(recommendid);--2019/02/22提交结果记录放在表tb_interview_record
//    Interview inv = interviewDAO.getByRecommendId(recommendid);
//    List<Interview> list = interviewDAO.getListByRecommendId(recommendid);
        List<RecommendRecord> recommendRecord = recomDAO.getRecordByid(recommendid);
        recommendRecord = recommendRecord.stream().filter(r -> ("合适".equals(r.getRemark()) || "不合适".equals(r.getRemark()))).collect(Collectors.toList());

        int createby = recommend.getCreateby();
        int platformid = recommend.getPlatformId();
        String createPerson = null;
        Employee emp = null;
        Hunter hunter = null;
        if (platformid == 1) {
            emp = employeeDAO.getByPersonId(createby);
            createPerson = person.getName() != null ? person.getName() : "";
        } else {
            hunter = hunterDAO.getById(createby);
            employer = employerDAO.getById(createby);
            if (hunter != null) {
                createPerson = hunter.getName();
            } else {
                createPerson = employer.getName();
            }

        }

        Company company = companyDAO.getById(person.getCompanyId());
        City city = cityDAO.getById(person.getCityId());
        String today = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        TbFile tbFile = tbFileDAO.getByPersonId(person.getId());
        Employee employee = employeeDAO.getByPersonId(person.getId());
        model.addAttribute("employee", employee);
        model.addAttribute("file", tbFile);
        model.addAttribute("createPerson", createPerson);
        model.addAttribute("interviews", recommendRecord);
        model.addAttribute("recommend", recommend);
        model.addAttribute("company", company);
        model.addAttribute("city", city);
        model.addAttribute("person", person);
        model.addAttribute("todayStr", today);
        //model.addAttribute("interviewId",inv.getId());
//    model.addAttribute("inv", inv);
        // logger.info("interviewrecode size view display="+list.size());
        //logger.info("interview inv="+inv.getId());
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hr/jobinterviewlist";
    }

    @RequestMapping(value = "wechat/hunter/hr/toInterviewRecord.do", method = RequestMethod.GET)
    public String toInterviewRecord(HttpServletRequest request, Integer interviewId, ModelMap model) {
        System.out.println("interviewId: " + interviewId);
        Interview interview = interviewDAO.getById(interviewId);
        List<InterviewRecord> list = interViewRecordDAO.getALL(interviewId);

        model.addAttribute("interview", interview);
        model.addAttribute("interviewRecords", list);

        String ticket = sysConfigService.getJsTicket();
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        return "wechat/headhunter/hr/jobinterviewRecord";
    }

    // 创建面试结果
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/creatInterview.do")
    public @ResponseBody
    Map<String, Object> createInterviewRecord(HttpServletRequest request, ModelMap model, String recommendid) {

        Map<String, Object> msg = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
//        openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.put("errorcode", -2);
            msg.put("msg", "您尚未注册我们服务");
            return msg;
        }
        InterviewRecord interview = new InterviewRecord();
        String status = request.getParameter("status");
        String updateTime = request.getParameter("updateTime");
        String interViewId = request.getParameter("interViewId");
        String itype = request.getParameter("itype");
        String remark = request.getParameter("remark");
        interview.setStatus(Integer.valueOf(status));
        interview.setRemark(remark);
        interview.setItype(Integer.valueOf(itype));
        interview.setCreateTime(updateTime);

        //interview.setRecommendId(recommendid);--20190222 update 反馈记录迁移tb_interview=>tb_interviewRecord
        interview.setInterviewId(Integer.valueOf(interViewId));
        interview.setCreateBy(employer.getId());
        Long interviewId = interViewRecordDAO.save(interview);
        if (interviewId <= 0) {
            msg.put("errorcode", -2);
            msg.put("msg", "操作错误");
            return msg;
        }

        if (interview.getStatus() == 3 || interview.getStatus() == 6 || interview.getStatus() == 8 || interview.getStatus() == 11) {

            int result = recomDAO.updateStatus(3, Integer.parseInt(recommendid));
            if (result <= 0) {
                msg.put("errorcode", 2);
                msg.put("msg", "更新状态失败");
                msg.put("data", interview);
                return msg;
            }
        }
        if (interview.getStatus() == 4 || interview.getStatus() == 5 || interview.getStatus() == 10) {
            int result = recomDAO.updateStatus(2, Integer.parseInt(recommendid));
            if (result <= 0) {
                msg.put("errorcode", 2);
                msg.put("msg", "更新状态失败");
                msg.put("data", interview);
                return msg;
            }
        }
        msg.put("errorcode", 0);
        msg.put("msg", "成功创建面试状态");
        msg.put("data", interview);

        return msg;
    }

    // 创建面试
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/updateInterviewStatus.do")
    public @ResponseBody
    Map<String, Object> updateInterviewStatus(HttpServletRequest request, ModelMap model, Interview interview) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();
        //session.setAttribute("OpenId", "o852IsyRIkwuLXZox-Z1ounYjDEc");
        String openid = (String) session.getAttribute("OpenId");

        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们服务");
            return returnMap;
        }

        Integer recommendid = Integer.valueOf(request.getParameter("recommendid"));
        if (StringUtils.isEmpty(recommendid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定推荐");
            return returnMap;
        }
        Recommendation recom = recomDAO.getById(String.valueOf(recommendid));
        Person person = personDAO.getById(recom.getPersonId());
        JobDesc job = jobDAO.getById(recom.getJobId());
        // Integer interviewid =
        // Integer.valueOf(request.getParameter("interviewid"));
        // if (StringUtils.isEmpty(interviewid)) {
        // returnMap.put("errorcode", -2);
        // returnMap.put("msg", "未指定面试");
        // return returnMap;
        // }
        /*
         * int result = recomDAO.updateStatus(0, recommendid); if(result <= 0) { returnMap.put("errorcode", -2);
         * returnMap.put("msg", "更新数据失败"); }
         *
         * result = interviewDAO.updateStatus(0, interviewid); if(result == 1) { returnMap.put("errorcode", 0);
         * returnMap.put("msg", "更新数据成功"); } else { returnMap.put("errorcode", -2); returnMap.put("msg", "操作失败"); }
         */
        String action = request.getParameter("action");
        if (StringUtils.isEmpty(action)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定操作类型");
            return returnMap;
        }

        Company company2 = companyDAO.getById(job.getCompanyId());
        if ("ask".compareToIgnoreCase(action) == 0) {  //面试邀请

//      Long count = interviewDAO.getCountOfAll(recommendid, 1);
            // 判断最新面试有没有记录反馈 & 反馈是否入职
            Interview temp = interviewDAO.getLastByRecommendId(recommendid);
            if (temp != null) {
                List<InterviewRecord> all = interViewRecordDAO.getALL(temp.getId());
                if (all == null || all.size() < 2) {
                    returnMap.put("errorcode", -2);
                    returnMap.put("msg", "请先完成上一轮面试反馈，再创建下一轮面试");
                    return returnMap;
                }
                for (InterviewRecord record : all) {
                    if (record.getStatus() == 10) {
                        returnMap.put("errorcode", -2);
                        returnMap.put("msg", "候选人已入职，无法创建下一轮面试");
                        return returnMap;
                    }
                }
            }

            Interview itv = new Interview();
            itv.setRecommendId(recommendid);
            itv.setItype(5);
            itv.setStatus(1);
            Date now = new Date();
            itv.setCreateTime(now.getTime());
            itv.setUpdateTime(new java.sql.Date(now.getTime()));
            itv.setInterviewDate(interview.getInterviewDate().replace("T", " "));
            itv.setInterviewSite(interview.getInterviewSite());
            itv.setInterviewer(interview.getInterviewer());

            itv.setInterviewContact(interview.getInterviewContact());
            itv.setRound(interview.getRound());
            itv.setCreateBy(employer.getId());
            Long interviewId = interviewDAO.save(itv);
            if (interviewId <= 0) {
                returnMap.put("errorcode", -2);
                returnMap.put("msg", "未指定操作类型");
                return returnMap;
            }
            itv.setId(interviewId.intValue());
            //推送消息给候选人start//
            //send msg 跳哪里服务号-面试邀约提醒
            String tempjsontiaos = TemplateData
                    .New()
                    .setTouser(person.getOpenid())
                    .setTemplate_id("3WuueX20Sq4pL4nU0DY1IcWG5q-MY-vs9Zx_ywoeVhw")
//					.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobid="
//							+ job.getId())
                    .add("first",
                            "您好,非常荣幸收到您的简历，招聘方经过评估，认为您与该职位的条件符合，邀请您进入面试阶段。", "#274084")
                    .add("keyword1", company2.getName(), "#000000")
                    .add("keyword2", job.getName(), "#F47e2d")
                    .add("keyword3", itv.getInterviewSite(), "#000000")
                    .add("keyword4", itv.getInterviewDate().replace("T", " "), "#000000")
                    .add("keyword5", "在医人才平台上看到您的简历符合我公司的人才要求，现邀请您在" + itv.getInterviewDate().replace("T", " ") + "至" + itv.getInterviewSite() + "，参加我公司面试。面试官信息：" + itv.getInterviewer() + "；联系方式：" + itv.getInterviewContact(), "#000000")
//					.add("remark", "订单请点击查看", "#000000")
                    .build();
            System.out.println(tempjsontiaos);
            ApiResult resulttiaos = WxaTemplateUtil.sendtiaonalis(tempjsontiaos);
            logger.info("HR查看了你的简历，推送消息给候选人结果=" + resulttiaos);
            //**推送结束end**/

            //我在MedTrend上看到了您的简历，我们[+变量+]公司经过一个初步审核觉得您比较适合我们公司。为了彼此进一步的了解，我们邀请您过来参加公司面试，面试时间/地址我们事先以电话联系，请您保持电话畅通，谢谢您。
            try {
                //短信发送给面试邀请人招聘之类的不能发送短信2018/04/13
                SMSService.sendSMSInterview(company2.getName(), person.getPhone(), itv.getInterviewDate().replace("T", " "),
                        itv.getInterviewSite(), itv.getInterviewer() + "&" + itv.getInterviewContact());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //记录
            InterviewRecord inr = new InterviewRecord();
            inr.setInterviewId(interviewId.intValue());
            inr.setItype(interview.getRound());
            inr.setStatus(1);
            inr.setRemark("已发面试邀请");
            inr.setCreateBy(employer.getId());
            //inr.setCreateTime(com.jeeplus.common.utils.DateUtils.getDateTime());
            Long countinr = interViewRecordDAO.save(inr);
            logger.info("interviewRecord创建面试记录值==" + countinr);
            recomDAO.updateStatus(1, recommendid);
            //记录结束//

            returnMap.put("errorcode", 0);
            returnMap.put("msg", "成功创建了面试");
            returnMap.put("data", itv);
            return returnMap;
        }
        return returnMap;
    }


    // ==============菜单入口：职位候选人列表
    // 发布的悬赏职位列表进而选择自由候选人
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/jobcandidatelist.page", method = RequestMethod.GET)
    public String jobCdList(HttpServletRequest request, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
//        openid="o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }
        if (employer.getBinded() != 1) {
            model.addAttribute("title", "信息审核中");
            model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
            return "wechat/headhunter/msgpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }

//    List<JobDesc> list = jobDAO.getJobDescCreatedBy(employer.getId(), offset);
        List<RecommendedPerson> list = recomDAO.getRecommendedPersonAll(employer.getId(), offset);
        if (list != null) {

            for (RecommendedPerson rd : list) {
                if (6 == rd.getStatus()) { //职位沟通确认
                    String name = rd.getName();
                    if (!StringUtils.isEmpty(name)) {
                        name = name.substring(0, 1) + "**";
                    }
                    rd.setName(name);
                }
                if (!StringUtils.isEmpty(rd.getOpenid())) {
                    UserInfo userInfo = userDAO.getByOpenId(rd.getOpenid());
                    userInfo = Optional.ofNullable(userInfo).orElse(new UserInfo());
                    rd.setAvatar(userInfo.getHeadimgurl());
                }
            }
        }
        /* model.addAttribute("total",recomDAO.getCount());*/
        model.addAttribute("recomlist", list);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hr/jobcandidatelist";
    }

    // 获取更多我的悬赏的列表信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/hr/morejobcandidate.do", method = RequestMethod.GET)
    public @ResponseBody
    ErrorMsg moreJobCdList(HttpServletRequest request, ModelMap model) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未提交认证信息");
            return msg;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonAll(employer.getId(), offset);
        /* config */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /**/

        msg.setErrorcode("0");
        msg.setMsg("获取数据成功");
        msg.setData(list);

        return msg;
    }


    //********************************猎头顾问职位列表
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/joblist.page", method = RequestMethod.GET)
    public String hunterJobList(HttpServletRequest request, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        //String openid="o852Is7ih5u1jnXnLaRixmqWn9zk";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }
        if (hunter.getBinded() != 1) {
            model.addAttribute("title", "信息审核中");
            model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
            return "wechat/headhunter/msgpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }

        List<JobDesc> list = jobDAO.getJobDescCreatedBy(hunter.getId(), offset, null);
        if (list != null) {
            for (JobDesc job : list) {
                long time = job.getExpiredDate();
                Date date = new Date(time);
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String str = bartDateFormat.format(date);
                job.setExpiredDateStr(str);

                long createDate = job.getCreateDate();
                job.setCreateDateStr(bartDateFormat.format(new Date(createDate)));

            }
        } else {
            list = new ArrayList<JobDesc>();
        }
        List<City> cities = cityDAO.getALL();
        model.addAttribute("jobList", list);
        model.addAttribute("cities", cities);
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        //url=url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */
        return "wechat/headhunter/hunter/joblist";
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hr/moreJob.do", method = RequestMethod.GET)
    public @ResponseBody
    ErrorMsg hrMoreJobList(HttpServletRequest request, ModelMap model, @RequestParam(value = "status", required = true) Integer status) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未提交认证信息");
            return msg;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        List<JobDesc> list = jobDAO.getJobDescCreatedBy(employer.getId(), offset, status);
        if (list != null) {
            for (JobDesc job : list) {
                long time = job.getExpiredDate();
                Date date = new Date(time);
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String str = bartDateFormat.format(date);
                job.setExpiredDateStr(str);
                //city
                long createDate = job.getCreateDate();
                job.setCreateDateStr(bartDateFormat.format(new Date(createDate)));

                int cityId = job.getCityId();
                City city = cityDAO.getById(cityId);
                job.setCity(city);
                Domain domain = domainDAO.getById(job.getDomainID());
                job.setDomainName(domain.getName());

            }
        } else {
            list = new ArrayList<JobDesc>();
        }
        msg.setErrorcode("0");
        msg.setMsg("获取数据成功");
        msg.setData(list);

        return msg;
    }

    // 职位候选人列表，点击后查看详细的职位信息及被推荐人列表
//    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toJobView.do", method = RequestMethod.GET)
    public String hunterOfJobViewwithRecommends(HttpServletRequest request, Integer jobid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (jobid == null || jobid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择的职位");
            return "wechat/headhunter/msgpage";
        }
        JobDesc job = jobDAO.getById(jobid);
        if (job == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的职位不存在");
            return "wechat/headhunter/msgpage";
        }

        long time = job.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        job.setExpiredDateStr(str);

        //---------------------------------职位候选人--------------------------------------
        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(jobid, 0);

        Company company = companyDAO.getById(job.getExpectcompanyid());

        List<City> cities = cityDAO.getALL();

        model.addAttribute("job", job);
        model.addAttribute("cities", cities);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);


        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

//    List<EmployeePerson> emps = employeeDAO.searchEmployeesByJob(job);

        //-----------------------系统匹配候选人--------------------------------
        List<EmployeePerson> emps = employeeDAO.searchDiffEmployeesByJob(job, jobid, 1);


        List<List<EmployeePerson>> resList = new ArrayList<List<EmployeePerson>>();
        List<EmployeePerson> temp = new ArrayList<EmployeePerson>();

        if (emps != null && emps.size() < 3) {
            resList.add(emps);
            model.addAttribute("emps", resList);
        } else {
            for (int i = 0; i < emps.size(); i++) {
                temp.add(emps.get(i));
                if ((i + 1) % 3 == 0) {
                    resList.add(temp);
                    temp = new ArrayList<EmployeePerson>();
                } else if (i == (emps.size() - 1)) {
                    resList.add(temp);
                }
            }
            model.addAttribute("emps", resList);
        }

        model.addAttribute("empslength", emps.size());
        return "wechat/headhunter/hunter/zhiweixiangxixinxi";
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toViewRecommend.do", method = RequestMethod.GET)
    public String viewRecommendHunter(HttpServletRequest request, Integer positionid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (positionid == null || positionid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择的职位");
            return "wechat/headhunter/msgpage";
        }
        JobDesc job = jobDAO.getById(positionid);
        if (job == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的职位不存在");
            return "wechat/headhunter/msgpage";
        }

        long time = job.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        job.setExpiredDateStr(str);

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(positionid, 0);

        Company company = companyDAO.getById(job.getExpectcompanyid());

        List<City> cities = cityDAO.getALL();

        model.addAttribute("job", job);
        model.addAttribute("cities", cities);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        //   List<Employee> emps = employeeDAO.searchEmployeesByJob(job);
        //   model.addAttribute("emps", emps);

        return "wechat/headhunter/hunter/recommendList";
    }


    //显示详细职位和候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toViewJob.page", method = RequestMethod.GET)
    public String toViewJobWithCandidateHunter(HttpServletRequest request, int positionid, ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的服务。");
            return "wechat/headhunter/msgpage";
        }
        JobDesc jd = jobDAO.getById(positionid);
        if (jd == null) {
            logger.error("can't find the job with the id " + positionid);
            return "wechat/headhunter/errorpage";
        }
        int cityid = jd.getCityId();
        City city = cityDAO.getById(cityid);
        jd.setCity(city);

        int companyid = jd.getCompanyId();
        Company company = companyDAO.getById(companyid);
        if (company != null) {
            jd.setCompanyName(company.getName());
        }

        int expcompanyid = jd.getExpectcompanyid();
        Company expCompany = companyDAO.getById(expcompanyid);
        jd.setExpCompanyName(expCompany.getName());

        if (!StringUtils.hasText(jd.getName())) {
            long roleid = jd.getRoleid();
            JobTitle role = roleDAO.getById(roleid);
            jd.setRole(role);
            jd.setName(role.getName());
        }
        long time = jd.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        // String str = DateUtil.getDateTimeStr(time);
        jd.setExpiredDateStr(str);

        model.addAttribute("employer", hunter);

        model.addAttribute("position", jd);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */
        // job title
        List<EmployeePerson> emps = employeeDAO.searchEmployeesByJob(jd);
        model.addAttribute("emps", emps);

        return "wechat/headhunter/fabuzhiwei2";
    }

    //    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toEditJob.page", method = RequestMethod.GET)
    public String toEditJobHunter(HttpServletRequest request, int positionid, ModelMap model) {
        HttpSession session = request.getSession();
//        String openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        JobDesc jd = jobDAO.getById(positionid);
        if (jd == null) {
            logger.error("can't find the Recommendation with the id " + positionid);
            return "wechat/headhunter/errorpage";
        }
        long time = jd.getExpiredDate();
        Date date = new Date(time);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String str = bartDateFormat.format(date);
        // String str = DateUtil.getDateTimeStr(time);
        jd.setExpiredDateStr(str);

        int companyId = jd.getCompanyId();
        Company comp = this.companyDAO.getById(companyId);
        comp.getDomain();

        List<Company> companies = companyDAO.getALL();
        List<City> cities = cityDAO.getALL();
        List<JobTitle> roles = roleDAO.getALL();
        model.addAttribute("companies", companies);
        model.addAttribute("cities", cities);
        model.addAttribute("roles", roles);

        model.addAttribute("position", jd);
        List<Domain> domains = domainDAO.getAllSubDomain();
        model.addAttribute("domains", domains);
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hunter/fabuzhiwei";
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/holdJobDesc.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> holdJobDescHunter(HttpServletRequest request, ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们服务");
            return returnMap;
        }

        Integer jobid = Integer.valueOf(request.getParameter("jobid"));
        if (StringUtils.isEmpty(jobid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定职位");
            return returnMap;
        }

        int result = jobDAO.holdJob(jobid);

        if (result == 1) {
            returnMap.put("errorcode", 0);
            returnMap.put("msg", "成功获取数据");
        } else {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "操作失败");
        }

        return returnMap;
    }

    // 获取更多职位的候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/moreJobRecommend.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> moreJobRecommendationHunter(HttpServletRequest request, ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            returnMap.put("errorcode", 500101);
            returnMap.put("msg", "你尚未注册我们的服务");
            return returnMap;
        }

        Integer jobid = Integer.valueOf(request.getParameter("jobid"));
        if (StringUtils.isEmpty(jobid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定职位");
            return returnMap;
        }

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonByPosition(jobid, offset);

        returnMap.put("errorcode", 0);
        returnMap.put("msg", "成功获取数据");
        returnMap.put("recommends", list);

        return returnMap;
    }

    // 获取更多我的悬赏的列表信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/moreJob.do", method = RequestMethod.GET)
    public @ResponseBody
    ErrorMsg moreHunterJobList(HttpServletRequest request, ModelMap model) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未提交认证信息");
            return msg;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        List<JobDesc> list = jobDAO.getJobDescCreatedBy(employer.getId(), offset, 1);
        if (list != null) {
            for (JobDesc job : list) {
                long time = job.getExpiredDate();
                Date date = new Date(time);
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String str = bartDateFormat.format(date);
                job.setExpiredDateStr(str);
            }
        } else {
            list = new ArrayList<JobDesc>();
        }

        msg.setErrorcode("0");
        msg.setMsg("获取数据成功");
        msg.setData(list);

        return msg;
    }

    // 创建职位
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/creatJob.do", method = RequestMethod.POST)
    public @ResponseBody
    ErrorMsg createJobDescByHunter(HttpServletRequest request, ModelMap model, JobDesc job) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.setErrorcode("500101");
            msg.setMsg("创建职位失败");
            return msg;
        }

        String jobname = job.getName();
        if (StringUtils.isEmpty(jobname)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("职位名不能为空");
            return msg;
        }
        JobTitle jobtitle = roleDAO.getByName(jobname);
        if (jobtitle == null) {
            // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
            job.setName(jobname);
            job.setRoleid(0);
        } else {
            // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
            job.setName(jobname);
            job.setRoleid(jobtitle.getId());
        }
        JobTitle jobT = roleDAO.getByName(job.getExpectJob());
        if (jobT == null) {
            // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
//     job.setExpectJob(job.get);
            job.setExpectJobId(0);
        } else {
            // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
//     job.setExpectJob(jobname);
            job.setExpectJobId(jobT.getId());
        }
        /*
         * if(job.getRoleid() > 0) { role = roleDAO.getById(job.getRoleid()); if(role != null) {
         * job.setName(role.getName()); } }
         */

        Date now = new Date();
        job.setCreateDate(now.getTime());
        String dateStr = job.getExpiredDateStr();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(dateStr);
            job.setExpiredDate(date.getTime());
        } catch (ParseException e) {
            msg.setErrorcode("500101");
            msg.setMsg("创建职位失败");
            return msg;
        }
        job.setCreatedby(employer.getId());

        int companyId = employer.getCompanyId();
        job.setCompanyId(companyId);

        // 这里要一个流水线号
        // Random rand = new Random();
        // String code = Integer.toString(rand.nextInt(99));
        String code = jobDAO.getJobCodeString();
        job.setJobCode("P-" + code);

        int id = jobDAO.save(job);
        if (id == -1) {
            msg.setErrorcode("-1");
            msg.setMsg("创建职位失败");
            return msg;
        }
        job.setId(id);
        msg.setErrorcode("0");
        msg.setMsg("成功创建职位");
        msg.setData(job);

        return msg;
    }

    //候选人的面试状态
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toInterview.do", method = RequestMethod.GET)
    public String hunterOfInterview(HttpServletRequest request, Integer recommendid, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "o852IsyRIkwuLXZox-Z1ounYjDEc");

        String openid = (String) session.getAttribute("OpenId");
//        openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }

        if (recommendid == null || recommendid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择哪个职位");
            return "wechat/headhunter/msgpage";
        }

        Recommendation recommend = recomDAO.getById(recommendid.toString());
        if (recommend == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您选择的推荐不存在");
            return "wechat/headhunter/msgpage";
        }

        Person person = personDAO.getById(recommend.getPersonId());
        if (person != null) {
            long roleId = person.getRoleId();
            JobTitle role = roleDAO.getById(roleId);
            if (role != null) {
                person.setRoleName(role.getName());
            }
        }

        List<Interview> list = interviewDAO.getByKey(recommendid);
        int createby = recommend.getCreateby();
        int platformid = recommend.getPlatformId();
        String createPerson = null;
        Employee emp = null;
        if (platformid == 1) {
            emp = employeeDAO.getByPersonId(createby);
            createPerson = person.getName();
        } else {
            hunter = hunterDAO.getById(createby);
            if (hunter != null) {
                createPerson = hunter.getName();
            }

        }
        Company company = companyDAO.getById(person.getCompanyId());
        City city = cityDAO.getById(person.getCityId());
        String today = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        TbFile tbFile = tbFileDAO.getByPersonId(person.getId());
        Employee employee = employeeDAO.getByPersonId(person.getId());
        model.addAttribute("employee", employee);
        model.addAttribute("file", tbFile);
        model.addAttribute("createPerson", createPerson);
        model.addAttribute("interviews", list);
        model.addAttribute("recommend", recommend);
        model.addAttribute("company", company);
        model.addAttribute("city", city);
        model.addAttribute("person", person);
        model.addAttribute("todayStr", today);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hunter/jobinterviewlist";
    }

    // 创建面试结果
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/creatInterview.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> createInterviewByHunter(HttpServletRequest request, ModelMap model, Interview interview) {

        Map<String, Object> msg = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        Employer employer = employerDAO.getByOpenId(openid);
        if (employer == null) {
            msg.put("errorcode", -2);
            msg.put("msg", "您尚未注册我们服务");
            return msg;
        }

        int recommendid = 0;
        String idStr = request.getParameter("recommendid");
        if (StringUtils.isEmpty(idStr)) {
            recommendid = 0;
        } else {
            recommendid = Integer.valueOf(idStr);
        }
        if (recommendid <= 0) {
            msg.put("errorcode", -2);
            msg.put("msg", "推荐不存在");
            return msg;
        }
        Recommendation recommend = recomDAO.getById(idStr);
        if (recommend == null) {
            msg.put("errorcode", -2);
            msg.put("msg", "推荐不存在");
            return msg;
        }
        if (recommend.getStatus() == 0) {
            msg.put("errorcode", 1);
            msg.put("msg", "你必须发送面试邀请，得到批准后才能开始进行面试");
            return msg;
        }

        interview.setRecommendId(recommendid);
        Long interviewId = interviewDAO.save(interview);
        if (interviewId <= 0) {
            msg.put("errorcode", -2);
            msg.put("msg", "操作错误");
            return msg;
        }
        interview.setId(interviewId.intValue());

        if (interview.getStatus() == 3) {
            int result = recomDAO.updateStatus(3, recommendid);
            if (result <= 0) {
                msg.put("errorcode", 2);
                msg.put("msg", "更新状态失败");
                msg.put("data", interview);
                return msg;
            }
        }
        if (interview.getStatus() == 4) {
            int result = recomDAO.updateStatus(2, recommendid);
            if (result <= 0) {
                msg.put("errorcode", 2);
                msg.put("msg", "更新状态失败");
                msg.put("data", interview);
                return msg;
            }
        }

        msg.put("errorcode", 0);
        msg.put("msg", "成功创建面试状态");
        msg.put("data", interview);

        return msg;
    }

    // 更新面试状态
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/updateInterviewStatus.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> updateInterviewStatusByHunter(HttpServletRequest request, ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们服务");
            return returnMap;
        }

        Integer recommendid = Integer.valueOf(request.getParameter("recommendid"));
        if (StringUtils.isEmpty(recommendid)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定推荐");
            return returnMap;
        }
        Recommendation recom = recomDAO.getById(String.valueOf(recommendid));
        Person person = personDAO.getById(recom.getPersonId());
        JobDesc job = jobDAO.getById(recom.getJobId());

        String action = request.getParameter("action");
        if (StringUtils.isEmpty(action)) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "未指定操作类型");
            return returnMap;
        }
        if ("ask".compareToIgnoreCase(action) == 0) {

            Long count = interviewDAO.getCountOfAll(recommendid, 1);
            if (count >= 1) {
                returnMap.put("errorcode", -2);
                returnMap.put("msg", "已经发送了面试邀请");
                return returnMap;
            }

            Interview itv = new Interview();
            itv.setRecommendId(recommendid);
            itv.setItype(5);
            itv.setStatus(1);
            Date now = new Date();
            itv.setCreateTime(now.getTime());
            itv.setUpdateTime(new java.sql.Date(now.getTime()));
            Long interviewId = interviewDAO.save(itv);
            if (interviewId <= 0) {
                returnMap.put("errorcode", -2);
                returnMap.put("msg", "未指定操作类型");
                return returnMap;
            }
            itv.setId(interviewId.intValue());
            //我在MedTrend上看到了您的简历，我们[+变量+]公司经过一个初步审核觉得您比较适合我们公司。为了彼此进一步的了解，我们邀请您过来参加公司面试，面试时间/地址我们事先以电话联系，请您保持电话畅通，谢谢您。
            try {
                //短信发送给面试邀请人招聘之类的不能发送短信2018/04/13
                //SMSService.sendSMSInterview(person.getPhone(), job.getCompanyName());
                // 推送msg于候选人
                Company company = companyDAO.getById(job.getCompanyId());
                if (person.getOpenid() != null && person.getOpenid() != "" && company != null) {
                    String tempjsonCandidate = TemplateData
                            .New()
                            .setTouser(person.getOpenid())
                            .setTemplate_id(
                                    "3WuueX20Sq4pL4nU0DY1IcWG5q-MY-vs9Zx_ywoeVhw")
                            .add("first",
                                    "您好,我们公司经过一个初步审核觉得您适合我们公司，为了彼此进一步的了解，我们邀请您过来参加公司" + company.getName() + "面试。", "#274084")
                            .add("keyword1", job.getName(), "#000000")
                            .add("keyword2", company.getAddress() != null ? company.getAddress() : "待定", "#F47e2d")
                            .add("keyword3", "待定",
                                    "#000000")
                            .add("keyword4", "在MedTrend上看到您的简历符合我公司的人才要求，现在想邀请您到我们公司面试，面试地址/时间与您电话沟通确定好后会发送一份面试邀请函给您。", "#000000")
                            .add("remark", "感谢您，HR与您进一步联系请您保持电话畅通，祝您生活愉快！如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。", "#000000")
                            .build();
                    ApiResult resCandidate = WxaTemplateUtil.sendtiaonalis(tempjsonCandidate);
                    System.out.println(resCandidate);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            returnMap.put("errorcode", 0);
            returnMap.put("msg", "成功创建了面试");
            returnMap.put("data", itv);
            return returnMap;

        }
        if ("bonus".compareToIgnoreCase(action) == 0) {
            Long count = interviewDAO.getCountOfAll(recommendid, 5);
            if (count >= 1) {
                returnMap.put("errorcode", -2);
                returnMap.put("msg", "奖金已经发放了");
                return returnMap;
            }

            Interview itv = new Interview();
            itv.setRecommendId(recommendid);
            itv.setItype(5);
            itv.setStatus(5);
            Date now = new Date();
            itv.setCreateTime(now.getTime());
            itv.setUpdateTime(new java.sql.Date(now.getTime()));
            Long interviewId = interviewDAO.save(itv);
            if (interviewId <= 0) {
                returnMap.put("errorcode", -2);
                returnMap.put("msg", "未指定操作类型");
                return returnMap;
            }
            itv.setId(interviewId.intValue());
            int result = recomDAO.updateStatus(2, recommendid);
            if (result <= 0) {
                returnMap.put("errorcode", 2);
                returnMap.put("msg", "更新状态失败");
                returnMap.put("data", itv);
                return returnMap;
            }
            returnMap.put("errorcode", 0);
            returnMap.put("msg", "成功创建了面试");
            returnMap.put("data", itv);
            return returnMap;
        }

        return returnMap;
    }


    // ==============菜单入口：职位候选人列表
// 发布的悬赏职位列表进而选择自由候选人
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/jobcandidatelist.page", method = RequestMethod.GET)
    public String jobCdListByHunter(HttpServletRequest request, ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid " + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的服务。");
            model.addAttribute("url", "wechat/employer/main.page");
            return "wechat/headhunter/msgpage";
        }
        if (hunter.getBinded() != 1) {
            model.addAttribute("title", "信息审核中");
            model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
            return "wechat/headhunter/msgpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonAll(hunter.getId(), offset);

        model.addAttribute("recomlist", list);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hunter/jobcandidatelist";
    }

    // 获取更多我的悬赏的列表信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/morejobcandidate.do", method = RequestMethod.GET)
    public @ResponseBody
    ErrorMsg moreJobCdListByHunter(HttpServletRequest request, ModelMap model) {

        ErrorMsg msg = new ErrorMsg();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            msg.setErrorcode("-1");
            msg.setMsg("您尚未关注我们");
            return msg;
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter == null) {
            msg.setErrorcode("500101");
            msg.setMsg("你尚未提交认证信息");
            return msg;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }

        List<RecommendedPerson> list = recomDAO.getRecommendedPersonAll(hunter.getId(), offset);
        /* config */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /**/

        msg.setErrorcode("0");
        msg.setMsg("获取数据成功");
        msg.setData(list);

        return msg;
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toViewCandidateDetail.do", method = RequestMethod.GET)
    public String toViewEmpDetail(HttpServletRequest request, Integer empid,
                                  Integer jobid, ModelMap model) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");

        if (empid == null || empid <= 0) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您必须指定选择哪个候选人");
            return "wechat/headhunter/msgpage";
        }
        EmployeePerson emp = this.employeeDAO.getByEpId(empid);
        if (emp == null) {
            emp = this.personDAO.getByEmpId(empid);
        }
        City city = this.cityDAO.getById(emp.getCityId());
        JobTitle job = this.roleDAO.getById(emp.getRoleId());
        model.addAttribute("employee", emp);
        model.addAttribute("cityName", city.getName());
        model.addAttribute("roleName", job.getName());

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        model.addAttribute("jobId", jobid);
        return "wechat/headhunter/hunter/candidateDetail";
    }

    public ApiConfig getApiConfig2() {
        ApiConfig ac = new ApiConfig();

        // 配置微信 API 相关常量
        ac.setToken(WebchatServiceConstant.TOKEN);
        ac.setAppId(WebchatServiceConstant.APPID_TIAONALIS);
        ac.setAppSecret(WebchatServiceConstant.APPSECRET_TIAONALIS);

        /**
         * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
         * 2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(false);
        ac.setEncodingAesKey(WebchatServiceConstant.EncodingAESKey_TIAONALIS);
        return ac;
    }

    public static ApiResult sendTemplate(String token, String jsonStr) {
        String jsonResult = HttpUtils.post(WebchatServiceConstant.sendApiUrl
                + token, jsonStr);
        return new ApiResult(jsonResult);
    }


    @RequestMapping(value="wechat/hr/viewResume.do")
    @ResponseBody
    public String viewResume(String docId){
        ClientBuilderConfiguration c = new ClientBuilderConfiguration();
        c.setSupportCname(false);
        OSS client = new OSSClientBuilder().build(QiNiuConfig.ALI_ENDPOINT, QiNiuConfig.ALI_ACCESS_KEY, QiNiuConfig.ALI_ACCESS_KEY_SECRET);
        GetObjectRequest getObjectRequest = new GetObjectRequest(QiNiuConfig.ALI_BUCKET_NAME, QiNiuConfig.ALI_DOC_LOCATION + docId);
        getObjectRequest.setProcess(QiNiuConfig.ALI_PROCESS);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(QiNiuConfig.ALI_BUCKET_NAME,
                QiNiuConfig.ALI_DOC_LOCATION+ docId);
        request.setProcess(QiNiuConfig.ALI_PROCESS);
        request.setExpiration(new Date(new Date().getTime() + 3600 * 1000));
        URL url = client.generatePresignedUrl(request);
        String resultUrl = URLDecoder.decode(url.toString()).replace("http", "https");
        return resultUrl;
    }
}
